var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var inviteuid = '';

var hb_info = '';

var screen_w = 320;

var timer = '';

Page({
  data: {
    util: util,
    tc: 0,
    org_name: '',
    
    isIphone_x: false,
    nav_bgColor: '#ffffff',

      indicatorDots: true,
      autoplay: true,
      interval: 4000,
      duration: 600,
      startTime:0, 

      
      uid: 0,
      token: 0,
      openid: 0,
      userinfo: {},

      ownerInfo: '',
      photos: '',
      img_w: 300,
      img_h: 300,


      isIphone:false,

      isShow: false,

      colorSet: '',

      hongbaoInfo: '',
      curTime: 0,
      colorIndex: 0,

      animation: '',//广告动画
      screen_h: 480,


      gg_img_w: 290,
      gg_img_h: 290 * 4 / 3,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
      mask: 'true'
    })
    
    var that = this;
    var ownerId = util.dataUid;
    wx.getSystemInfo({
      success: function (res) {
        var isiPhone = (res.model.indexOf('iPhone') >= 0);
        screen_w = res.windowWidth;
        that.getJXSInfo(ownerId);
        that.setData({
          screen_h: res.windowHeight,
          gg_img_w: screen_w - 60,
          gg_img_h: (screen_w - 60) * 1.75
        })
      }
    })
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid,
          userinfo: res
        });
      }
    });

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck",
        "tc": that.data.tc
      },
      success: function (responseData) {
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    this.animation = wx.createAnimation({
      // 动画持续时间，单位ms，默认值 400
      duration: 300,
      /**
       * http://cubic-bezier.com/#0,0,.58,1  
       *  linear  动画一直较为均匀
       *  ease    从匀速到加速在到匀速
       *  ease-in 缓慢到匀速
       *  ease-in-out 从缓慢到匀速再到缓慢
       * 
       *  http://www.tuicool.com/articles/neqMVr
       *  step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
       *  step-end   保持 0% 的样式直到动画持续时间结束        一闪而过
       */
      timingFunction: 'linear',
      // 延迟多长时间开始
      delay: 0,
      /**
       * 以什么为基点做动画  效果自己演示
       * left,center right是水平方向取值，对应的百分值为left=0%;center=50%;right=100%
       * top center bottom是垂直方向的取值，其中top=0%;center=50%;bottom=100%
       */
      transformOrigin: 'center bottom 0',
    });

  },

  onShow: function () {
    if(util.appType == 3){//收取费用的app

    }
    //读取红包弹出广告信息
    this.loadHongbaoList();
    this.startTimer();
  },

  getJXSInfo: function (ownerId) {
    var that = this;
    app.GetUserInfo(ownerId, function (res) {
      wx.setNavigationBarTitle({
        title: res.realname ? res.realname : res.uname,
      })
      var images = '';
      var w = screen_w - 20;
      if (res.photo) {
        images = res.photo.split(',');
        var len = images.length;
        if (len >= 3) {
          w = (w - 10) / 3;
        } else {
          w = (w - 5 * (len - 1)) / len;
        }
      }
      console.log("门店信息：", res);
      that.setData({
        ownerInfo: res,
        photos: images,
        img_w: w,
        img_h: w
      });
      
      wx.hideLoading();
    });
  },

  goMapView: function () {
    var lat = parseFloat(this.data.ownerInfo.lat);
    var lon = parseFloat(this.data.ownerInfo.lon);
    var name = this.data.ownerInfo.realname ? this.data.ownerInfo.realname : this.data.ownerInfo.uname;
    var addr = this.data.ownerInfo.address;

    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 18,
      name: name,
      address: addr,
    })
  },

  makeCallPhone: function (e) {
    var phoneNum = (this.data.ownerInfo.has_app && this.data.ownerInfo.has_app != '0') ? this.data.ownerInfo.has_app : this.data.ownerInfo.phone;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("朋友圈图片链接：" + shareImgUrl);
    var that = this;
    wx.previewImage({
      current: shareImgUrl,
      urls: that.data.photos
    })
  },

  

  // 定时器
  startTimer: function () {
    var that = this;
    timer = setTimeout(function () {
      var count = that.data.colorIndex + 1;
      that.setData({
        colorIndex: count
      })
      that.startTimer();
    }, 500);
  },

  onHide: function () {
    clearTimeout(timer);
  },

  resetNavColor: function(){
    // var bg_color = '#d8202d';
    // var fg_color = '#ffffff';
    // if (this.data.colorSet) {
    //   var colorJO = this.data.colorSet;
    //   bg_color = colorJO.titlebg;
    //   fg_color = colorJO.titlefont;
    // }
    // wx.setNavigationBarColor({
    //   frontColor: fg_color,
    //   backgroundColor: bg_color
    // })
  },


  //获取广告信息
  loadGuanggaoImage: function () {
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "getadlist"
    };
    util.api({
      data: params,
      success: function (responseData) {
        console.log("广告数据：", responseData);
        var result = responseData.data;
        if (result && result.length > 0) {
          for (var i = 0; i < result.length; i++) {
            var gdData = result[i];
            var key = "guanggao" + gdData.id;//本地缓存key
            var count = parseInt(gdData.preday ? gdData.preday : '1');//每天最大显示次数
            var startTime = parseInt(gdData.stime);//开始显示时间
            var endTime = parseInt(gdData.etime);//结束显示时间
            var curTime = parseInt(new Date().getTime() / 1000);
            if (startTime <= curTime && curTime <= endTime  //在规定时段内显示
              && parseInt(gdData.coinnum) > 0  //广告点数还没用完
              && app.getShowGuanggaoSign(key, count)) {//今天还有显示额度
              //广告
              result[i].key = key;
              that.setData({
                guanggao_link: result[i]
              });
              break;
            }
          }
        }
      }
    });

  },

  //获取红包列表信息
  loadHongbaoList: function () {
    var that = this;
      var params = {
        "publickey": util.publiccode,
        "ac": "hongbaolist",
        "uid": util.orgid
      };
      util.api({
        data: params,
        success: function (responseData) {
          var result = responseData.data;
          console.log("红包列表信息：", result);
          if (result && result.length > 0) {
            var time = parseInt((new Date().getTime()) / 1000);
            if (time <= result[0].endtime) {
              that.setData({
                hongbaoInfo: result[0],
                curTime: time,
              })
              if (time >= result[0].starttime && time <= result[0].endtime) {
                that.setData({
                  guanggao_link: result[0]
                })
              } else {
                that.loadGuanggaoImage();
              }
            } else {
              that.loadGuanggaoImage();
            }

          } else {
            that.loadGuanggaoImage();
          }
        }
      });
    
  },

  imageLoaded: function (e) {
    var data = e.currentTarget.dataset.info;
    
    if (!app.getShowHongBaoSign("hongbao") && data.hongbaoid) {
      //如果是红包，间隔时间不够，那么就不弹出
      // console.log("如果是红包，间隔时间不够，那么就不弹出");
      return;
    }

    var that = this;
    var showTime = 4000;
    if(data.showtime){
      showTime = parseInt(data.showtime);
    }
    setTimeout(function () {
      that.animation.translateY(-that.data.screen_h).step();
      that.setData({
        animation: that.animation.export(),
      })
      //计费
      if (that.data.loginuid && that.data.token) {//登录用户才计费
        that.adcoindown(data.id);
      }
    }, showTime);

    this.animation.translateY(this.data.screen_h).step();
    that.setData({
      animation: this.animation.export(),
    });

    console.log("更新广告标识：", data);
    if(data && data.key){
      //更新广告显示标识
      app.setShowGuanggaoSign(data.key);
    } else if (data.hongbaoid){
      //更新红包显示标识
      app.setShowHongBaoSign("hongbao");
    }
    
  },

  //扣除广告费用
  adcoindown: function (adid) {
    // 请求类型：post
    // 参数：ac - adcoindown标识接口
    // id - 广告id
    // downcoin - 扣除计费点数数值
    // 返回数据：res - true成功 false- 失败
    var that = this;
    var privatekey = utilMd5.hexMD5(this.data.loginuid + 'adcoindown' + this.data.token);
    var params = {
      ac: "adcoindown",
      privatekey: privatekey,
      uid: this.data.loginuid,
      id: adid,
      downcoin: 1
    };
    util.api({
      data: params,
      method: 'POST',
      success: function (responseData) {
        console.log('扣除广告费用点数: ', responseData);
      }
    });
  },

  //广告图响应动作
  guanggaoAction: function (e) {
    var data = e.currentTarget.dataset.info;
    if (data) {
      var go_type = data.linktype;
      var link = data.linkurl;
      if (go_type == "0" && link) {//去详情页
        var url = "/pages/detail/detail?topicid=" + link;
        wx.navigateTo({ url: url })
      } else if (go_type == "1" && link.indexOf('/pages/') >= 0) {
        wx.navigateTo({ url: link })
      }
    }
  },


  goAtherPage: function(e){
      var url = e.currentTarget.dataset.link;
      wx.navigateTo({url: url})
  },
  goAtherPageRedirect: function(e){
      var url = e.currentTarget.dataset.link;
      wx.redirectTo({url: url})
  },

  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    
    return {
      title: that.data.org_name,
      path: '/pages/index/index?&inviteuid=' + inviteuid
    };
  },
  

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if(path){
      wx.redirectTo({ url: path });
    }
    path = e.detail.value.page_path;
    if (path) {
      wx.navigateTo({ url: path });
    }
  },

  makeCallPhone:function(e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success:function(e){
        console.log("make call success:", JSON.stringify(e));
      },
      fail:function(e){
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },

  goHongbaoPage: function(e){
    var hb_info = e.currentTarget.dataset.info;
    var hongbaoId = hb_info.hongbaoid;
    var shareUid = hb_info.shareuid;
    var path = "/pages/hongbao/hongbao?hongbaoid=" + hongbaoId + "&shareuid=" + shareUid;
    wx.navigateTo({
      url: path,
    })
  },

  myShowToast: function(){
    wx.showToast({
      title: '未开通',
      icon: 'loading'
    })
  }
})
